package shaka.db.internal;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;
import org.logicalcobwebs.proxool.ProxoolException;
import org.logicalcobwebs.proxool.ProxoolFacade;

import shaka.db.provider.IConnectionProvider;
import shaka.db.provider.IProxoolProvider1;

public class ProxoolContainer1 implements IConnectionProvider {
	private Properties info = new Properties();
	private final String name;
	private final String alias;

	public ProxoolContainer1(IProxoolProvider1 provider) {
		try {
			name = provider.getAlias();
			this.alias = String.format("proxool.%s", name);

			int maxCnt = provider.maxConnectionCount();
			String driver = provider.getJdbcDriver();
			String url = provider.getJdbcUrl();
			String user = provider.getJdbcUser();
			String pwd = provider.getJdbcPassword();
			String testSql = provider.testSql();

			if (maxCnt > 0) {
				info.setProperty("proxool.maximum-connection-count", String.valueOf(maxCnt));
			} else {
				info.setProperty("proxool.maximum-connection-count", "1");
			}
			if (StringUtils.isNotEmpty(testSql)) {
				info.setProperty("proxool.house-keeping-test-sql", testSql);
			}
			if (StringUtils.isNotEmpty(user)) {
				info.setProperty("user", user);
			}
			if (StringUtils.isNotEmpty(pwd)) {
				info.setProperty("password", pwd);
			}
			ProxoolFacade.registerConnectionPool(String.format("proxool.%s:%s:%s", name, driver, url), info);
		} catch (ProxoolException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String getAlias() {
		return name;
	}

	@Override
	public Connection getConnection() throws SQLException {
		return DriverManager.getConnection(alias);
	}
}
